package com.scalar.chiptrack.adaptor.jobs;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.db.DBTransaction;
import com.scalar.chiptrack.db.DBXException;
import com.scalar.chiptrack.operations.reports.dao.WipFlushDAO;
import com.scalar.chiptrack.operations.orderscheduling.dao.OrderSchedulingDAO;
import com.scalar.chiptrack.utils.ConfigManager;
import com.scalar.chiptrack.utils.Mailer;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.commons.Labels;
import com.scalar.chiptrack.sales.LineItem;
import com.scalar.chiptrack.users.dao.UserDAO;
import com.scalar.chiptrack.users.Functionality;
import com.scalar.ScalarException;

import java.util.ArrayList;

import org.apache.struts.util.MessageResources;

/**
 * User: Sujan
 * Date: Feb 20, 2007
 * Time: 3:29:20 PM
 */
public class WipFlushShippableJob extends JobHandler
{
    public void execute() throws Exception
    {
        DBTransaction dbTranasaction = null;
        boolean success = false;
        ArrayList lineItemList = new ArrayList();
        try
        {
            //dbTranasaction = DBTransaction.getInstance();
            //dbTranasaction.begin();

            WipFlushDAO.createWipFlushSetup(dbTranasaction);
            WipFlushDAO.calculateWipFlushQuantities(dbTranasaction,0);

            //RE ALLOCATING ALL SCHEDULED LINE ITEMS
            lineItemList = OrderSchedulingDAO.reAllocateAllBackLog(dbTranasaction, null);

            if ( dbTranasaction != null )
            {
                dbTranasaction.commit();
            }
            success = true;
        }
        catch ( ScalarException e )
        {
            throw new ScalarException ( "Could not calculate Wip Flush Shippables", e );
        }
        finally
        {
            if ( dbTranasaction != null )
            {
                if ( !success )
                {
                    try { dbTranasaction.rollback(); } catch( DBXException ignore ){}
                }
            }
        }
        try
        {
            sendAlert( lineItemList );
        }
        catch ( Exception e )
        {
            throw new ScalarException ( "Could not send Missed Scheduled Orders Mail Alert", e );
        }
    }

    public static void main( String[] args ) throws Exception
    {
        new WipFlushShippableJob().execute();
    }

    private void sendAlert( ArrayList lineItemList ) throws Exception
	{
		String from = ConfigManager.getSysAdminEmail();
        ArrayList emailList = UserDAO.loadUserMailIDsByAuthorization( Functionality.ORDER_SCHEDULING );
        if( emailList == null || emailList.isEmpty() )
        {
            System.out.println( "There are zero users to notify... exiting" );
            return;
        }
        String[] emails = new String[emailList.size()];
        emailList.toArray(emails);
        String to = StringUtils.concatStrings( emails, Mailer.EMAIL_SEPARATOR );
		String subject = "Missed Scheduled LineItems";
		String message = createMessageBody ( lineItemList );
        if ( message != null && message.length() > 0 )
        {
            Mailer.send ( from, to, null, null, subject, message, null, Mailer.CONTENT_TYPE_HTML, false );
        }
    }

    private String createMessageBody ( ArrayList lineItemList )
    {
        StringBuffer messageBody = new StringBuffer();
        int lineItemListSize = ( lineItemList == null ) ? 0 : lineItemList.size();
        boolean foundLineItems = false;
        if( lineItemListSize > 0 )
        {
            String MFG_PART_NUMBER_KEY;
            try
            {
                 MFG_PART_NUMBER_KEY = MessageResources.getMessageResources( Labels.APPLICATION_RESOURCE_PROPERTIES ).getMessage( "label.mfgPartNumber" );
            }
            catch ( NullPointerException e )
            {
                 MFG_PART_NUMBER_KEY = Labels.DEFAULT_MFG_PART_NUMBER_LABEL;
            }
            messageBody.append( "<HTML><HEAD><TITLE>Scalarsoft - ChipTrac</TITLE><META http-equiv=Content-Type content='text/html; charset=windows-1252'></HEAD><BODY>" );
            messageBody.append ( "The following table describes scheduled LineItems which are missed according to the current inventory.<br> Please <b>ReSchedule</b> the following LineItems to ship in time." );
            messageBody.append( "<table ALIGN = 'CENTER' style='FONT-SIZE: 8pt; COLOR: black; FONT-FAMILY: Verdana' borderColor='#ffffff' cellSpacing='1' cellPadding='3' width='50%' border=0><tr bgColor='#ccccff'><td colspan='8' align='center'><b>Missed Scheduled LineItems</b></td></tr>" );
            messageBody.append( "<tr bgColor='#e6e6e6'>" );
            messageBody.append( "<td width='13%' align='center'><b>Sales Order #</b></td>" );
            messageBody.append( "<td width='8%' align='center' ><b>Line Item #</b></td>" );
            messageBody.append( "<td width='13%' align='center'><b>Customer</b></td>" );
            messageBody.append( "<td width='20%' align='center'><b>" + MFG_PART_NUMBER_KEY + "</b></td>" );
            messageBody.append( "<td width='10%' align='center'><b>Quantity</b></td>" );
            messageBody.append( "<td width='12%' align='center'><b>Booking Date</b></td>" );
            messageBody.append( "<td width='12%' align='center'><b>Req. Dock Date</b></td>" );
            messageBody.append( "<td width='12%' align='center'><b>Schedule Date</b></td>" );
            messageBody.append( "</tr>" );

            for( int i = 0; i < lineItemListSize; i++ )
            {
                LineItem lineItem = (LineItem)lineItemList.get( i ) ;
                if ( !"SUCCESS".equalsIgnoreCase( lineItem.getReason() ) )
                {
                    foundLineItems = true;
                    messageBody.append( "<tr bgColor='#e6e6e6'>" );
                    messageBody.append( "<td width='13%' align='center'>" + lineItem.getSalesOrderNo() + "</td>" );
                    messageBody.append( "<td width='8%' align='center'>" + lineItem.getLineItemNo() + "</td>" );
                    messageBody.append( "<td width='13%' align='center'>" + lineItem.getCustomerName() + "</td>" );
                    messageBody.append( "<td width='20%' align='center'>" + lineItem.getManufacturingPartNo() + "</td>" );
                    messageBody.append( "<td width='10%' align='center'>" + lineItem.getQuantity() + "</td>" );
                    messageBody.append( "<td width='12%' align='center'>" + lineItem.getBookingDate() + "</td>" );
                    messageBody.append( "<td width='12%' align='center'>" + lineItem.getRequestDate() + "</td>" );
                    messageBody.append( "<td width='12%' align='center'>" + lineItem.getScheduleDate()+ "</td>" );
                    messageBody.append( "</tr>" );
                }

            }
            messageBody.append( "<br><br></BODY></HTML>\n" );
        }
        if ( !foundLineItems )
        {
            return "";
        }
        else
        {
            return messageBody.toString();
        }
    }
}
